package com.srwl.mytx.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.widget.NestedScrollView;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.alibaba.fastjson.JSONObject;
import com.amap.api.location.AMapLocation;
import com.bm.library.Info;
import com.huantansheng.easyphotos.EasyPhotos;
import com.huantansheng.easyphotos.callback.SelectCallback;
import com.huantansheng.easyphotos.models.album.entity.Photo;
import com.smarx.notchlib.INotchScreen;
import com.smarx.notchlib.NotchScreenManager;
import com.srwl.mytx.Helper;
import com.srwl.mytx.utils.DateUtils;
import com.srwl.easeui.widget.MyTitleBar;
import com.srwl.mytx.Constant;
import com.srwl.mytx.R;
import com.srwl.mytx.RetrofitManager;
import com.srwl.mytx.adapter.PickPictureAdapter;
import com.srwl.mytx.domain.AliOssService;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.domain.FileUpLoad;
import com.srwl.mytx.domain.Item;
import com.srwl.mytx.domain.LatLng;
import com.srwl.mytx.domain.MyFile;
import com.srwl.mytx.domain.Topic;
import com.srwl.mytx.domain.User;
import com.srwl.mytx.map.GaodeLocationClient;
import com.srwl.mytx.parse.UserProfileManager;
import com.srwl.mytx.service.TopicService;
import com.srwl.mytx.utils.FileUtils;
import com.srwl.mytx.utils.GlideEngine;
import com.srwl.mytx.utils.MoneyInputCheck;
import com.srwl.mytx.utils.PayUtils;
import com.srwl.mytx.utils.PermissionsUtils;
import com.srwl.mytx.utils.SoftKeyboardFixerForFullscreen;
import com.srwl.mytx.utils.Utils;
import com.srwl.mytx.widget.PreviewSelectFilePageView;
import com.srwl.mytx.widget.ConfirmDialog;
import com.srwl.mytx.widget.DateChooseDialog;
import com.srwl.mytx.widget.PayPasswordDialog;
import com.srwl.mytx.widget.PickPicturesListView;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class EditTopicActivity extends BaseActivity implements PreviewSelectFilePageView.GetPhotoViewInfoListener, PickPictureAdapter.InteractionListener, PermissionsUtils.IPermissionsResult {
    public static void startActivity(Context context, Topic topic) {
        context.startActivity(new Intent(context, EditTopicActivity.class).putExtra(Constant.EXTRA_INFO_TOPIC, topic));
    }

    private static final String TAG = "EditTopicActivity";
    public static final String TOPIC_TYPE_EXPOSE = "曝光";
    public static final String TOPIC_TYPE_REWARD = "悬赏";
    public static final String TOPIC_TYPE_FIND_SOME_THING = "寻物";
    public static final String TOPIC_TYPE_FOUND = "招领";
    public static final String TOPIC_TYPE_GIFT = "赠送";
    public static final String TOPIC_TYPE_SHOW = "SHOW";
    public static final String TOPIC_TYPE_GOODS = "出售";
    public static final String TOPIC_TYPE_AUCTION = "拍卖";
    public static final String TOPIC_TYPE_OTHER = "其他";

    private Topic topic;
    private static final int REQUEST_CODE_PICTURE_CHOOSE = 1;
    private static final int REQUEST_CODE_RECORD_VIDEO = 2;
    private static final int REQUEST_CODE_LOCATION = 3;
    private static final int SITUATION_FOR_PUBLISH = 102;// 表示拍摄视频的质量和大小都按上限处理

    private float density;
    @BindView(R.id.tv_starting_date)
    TextView tv_startDate;
    @BindView(R.id.tv_stop_date)
    TextView tv_stopDate;
    @BindView(R.id.rv_add_picture)
    PickPicturesListView picturesListView;
    @BindView(R.id.ll_auction)
    View ll_acution;

    @BindView(R.id.et_goods_description)
    EditText et_content;
    @BindView(R.id.et_goods_title)
    EditText et_goodsTitle;
    @BindView(R.id.et_normal_price)
    EditText et_normalPrice;//普通出售商品价格
    @BindView(R.id.et_deposit)
    EditText et_deposit;//拍卖价格
    @BindView(R.id.et_bid_increment)
    EditText et_bidIncrement;

    @BindView(R.id.title_bar)
    MyTitleBar titleBar;
    @BindView(R.id.rl_normal_price)
    View rl_NormalPrice;
    @BindView(R.id.tv_price_tag)
    TextView tv_priceTag;
    @BindView(R.id.sv_container)
    NestedScrollView sv_container;
    @BindView(R.id.progress_bar)
    ProgressBar progressBar;
    @BindView(R.id.big_picture_page_view)
    PreviewSelectFilePageView previewSelectFilePageView;
    @BindView(R.id.rl_location)
    RelativeLayout rl_location;
    @BindView(R.id.tv_address)
    TextView tv_address;
    @BindView(R.id.btn_publish)
    Button btn_publish;
    private List<String> imagePaths = new ArrayList<>();
    private int pictureLimit = 9;//默认设置9张图片
    private int videoLimit = 1;//默认设置1个视频
    private List<MyFile> totalSelectFile = new ArrayList<>();
    private ArrayList<MyFile> selectRemotePictures = new ArrayList<>();//选择的历史图片 文件
    private ArrayList<MyFile> selectRemoteVideos = new ArrayList<>();//选择的历史 视频文件
    private ArrayList<MyFile> selectLocalPictures = new ArrayList<>();//选择的本地 图片文件
    private ArrayList<MyFile> selectLocalVideos = new ArrayList<>();//选择的本地 视频文件
    private ArrayList<Photo> selectPhotos = new ArrayList<>();//本地圖片 path 集合
    private List<String> originalImagePathPaths = new ArrayList<>();
    private List<Item> itemList = new ArrayList<>();
    private GaodeLocationClient location;
    private LocalBroadcastManager BrbroadcastManager;
    private String str_address;
    private boolean isUpdate;

    private LatLng latLng;
    //视频封面图片
    private String framePicPath;
    //视频大小
    private int videoSize;
    //主题分类
    private Integer topicType;
    private Date startDate;//拍卖开始时间
    private Date stopDate;//拍卖结束时间

    private Double newPrice;
    private boolean hasNotch;
    private MoneyInputCheck inputCheck;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit_topic);
        ButterKnife.bind(this);
        View statusBar = findViewById(R.id.status_bar);

        NotchScreenManager.getInstance().getNotchInfo(this, new INotchScreen.NotchScreenCallback() {
            @Override
            public void onResult(INotchScreen.NotchScreenInfo notchScreenInfo) {
                hasNotch = notchScreenInfo.hasNotch;
                Log.i(TAG, "Is this screen notch? " + hasNotch);
                if (hasNotch) {
                    statusBar.setVisibility(View.GONE);
                } else {
                    //如果不是刘海屏，就设置为全屏
                    SoftKeyboardFixerForFullscreen.assistActivity(EditTopicActivity.this);
                    setupStartBar();
                    int statusBarHeight = Utils.getStatusBarHeight(EditTopicActivity.this);
                    if (statusBarHeight != 0) {
                        ViewGroup.LayoutParams layoutParams = statusBar.getLayoutParams();
                        layoutParams.height = statusBarHeight;
                        statusBar.setLayoutParams(layoutParams);
                    }
                }
                previewSelectFilePageView.init(totalSelectFile, EditTopicActivity.this, hasNotch);
            }
        });
        topic = getIntent().getParcelableExtra(Constant.EXTRA_INFO_TOPIC);
        if (topic == null) {
            return;
        }
        if (!TextUtils.isEmpty(topic.getVideo())) {
            selectRemoteVideos.add(new MyFile(topic.getVideo(), topic.getVideoCover(), MyFile.FILE_TYPE_VIDEO, MyFile.FILE_STATUS_REMOTE));
        }
        totalSelectFile.addAll(selectRemoteVideos);
        imagePaths = topic.getPictures();
        originalImagePathPaths.addAll(imagePaths);
        et_goodsTitle.setText(topic.getTitle());
        et_content.setText(topic.getContent());
        density = getResources().getDisplayMetrics().density;
        for (String imagePath : imagePaths) {
            selectRemotePictures.add(new MyFile(imagePath, MyFile.FILE_TYPE_PICTURE, MyFile.FILE_STATUS_REMOTE));
        }
        totalSelectFile.addAll(selectRemotePictures);
        picturesListView.init(totalSelectFile, this);

        if (topic.getLocation() != null) {
            str_address = topic.getAddress();
            latLng = topic.getLocation();
            tv_address.setText(str_address);
        } else {
            initLocation();
        }

        sv_container.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
            @Override
            public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                hideSoftKeyboard();
            }
        });
        initTitleBar();
        //如果是焦点类型，
        if (topic.getType() == Constant.TOPIC_TYPE_SCHOOL || topic.getType() == Constant.TOPIC_TYPE_AREA || topic.getType() == Constant.TOPIC_TYPE_INDUSTRY) {

            if (topic.getStatus() == Constant.TOPIC_STATUS_NORMAL) { //状态是普通状态，非审核失败状态和等待审核状态，那么禁止对标题编辑
                et_goodsTitle.setEnabled(false);
//                et_goodsTitle.setOnClickListener(v -> {
//                    ConfirmDialog dialog = new ConfirmDialog(EditTopicActivity.this, "提示", "暂时不能编辑标题");
//                    dialog.show();
//                });
            }

        }
    }

    private void initTitleBar() {
        if (topic.getType() != null) {
            topicType = topic.getType();
            showType(topicType);
        }
        RelativeLayout.LayoutParams rightImagelayoutParams = new RelativeLayout.LayoutParams((int) (30 * density), (int) (30 * density));
        rightImagelayoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);
        //rightImagelayoutParams.addRule(RelativeLayout.ALIGN_PARENT_END);
        //  rightImagelayoutParams.setMarginEnd((int) (5 * density));
        //RightImage设置布局参数（setLayoutParams）应该在设置图片资源id（setImageResource）之后
        titleBar.getRightImage().setLayoutParams(rightImagelayoutParams);
        titleBar.setLeftLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPress();
            }
        });
        //如果是为其它或者聊天室类型主题,则直接返回
        if (topicType == Constant.TOPIC_TYPE_SCHOOL || topicType == Constant.TOPIC_TYPE_AREA || topicType == Constant.TOPIC_TYPE_INDUSTRY || topicType == Constant.TOPIC_TYPE_OTHER) {
            return;
        }
        final List<String> menuItems = new ArrayList<>();
        menuItems.add(TOPIC_TYPE_EXPOSE);
        menuItems.add(TOPIC_TYPE_REWARD);

//        titleBar.setRightLayoutClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                hideSoftKeyboard();
//
//                final ListPopupWindow listPopupWindow = new ListPopupWindow(EditTopicActivity.this);
//                listPopupWindow.setAdapter(new ArrayAdapter<String>(EditTopicActivity.this, R.layout.right_menu_item, R.id.tv_dialog_item, menuItems));
//                listPopupWindow.setAnchorView(titleBar.getRightLayout());
//                listPopupWindow.setWidth(Utils.dpToPx(130, EditTopicActivity.this));
//                listPopupWindow.setHeight(ListPopupWindow.WRAP_CONTENT);
//                listPopupWindow.setHorizontalOffset(Utils.dpToPx(-85, EditTopicActivity.this));
//                listPopupWindow.setVerticalOffset(Utils.dpToPx(2, EditTopicActivity.this));
//                listPopupWindow.setBackgroundDrawable(getResources().getDrawable(R.drawable.tx_pop_bg_1));
//                listPopupWindow.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//                    @Override
//                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                        switch (menuItems.get(position)) {
//                            case TOPIC_TYPE_EXPOSE:
//                                topicType = Constant.TOPIC_TYPE_EXPOSE;
//                                break;
//                            case TOPIC_TYPE_REWARD:
//                                topicType = Constant.TOPIC_TYPE_LOST_PEOPLE;
//                                break;
//                            case TOPIC_TYPE_FIND_SOME_THING:
//                                topicType = Constant.TOPIC_TYPE_REWARD;
//                                break;
//                            case TOPIC_TYPE_FOUND:
//                                topicType = Constant.TOPIC_TYPE_FOUND;
//                                break;
//
//                            case TOPIC_TYPE_GIFT:
//                                topicType = Constant.TOPIC_TYPE_GIFT;
//                                break;
//                            case TOPIC_TYPE_SHOW:
//                                topicType = Constant.TOPIC_TYPE_SHOW;
//                                break;
//                            case TOPIC_TYPE_GOODS:
//                                topicType = Constant.TOPIC_TYPE_GOODS;
//                                break;
//                            case TOPIC_TYPE_AUCTION:
//                                topicType = Constant.TOPIC_TYPE_AUCTION;
//                                break;
//
//                        }
//                        showType(topicType);
//                        listPopupWindow.dismiss();
//
//                    }
//                });
//                listPopupWindow.show();
//
//            }
//        });
    }

    private void showType(int topicType) {

        switch (topicType) {
            case Constant.TOPIC_TYPE_EXPOSE:
                titleBar.setRightTitle(EditTopicActivity.TOPIC_TYPE_EXPOSE);
                hidePriceLayout();
                break;
            case Constant.TOPIC_TYPE_REWARD:
                titleBar.setRightTitle(EditTopicActivity.TOPIC_TYPE_REWARD);
                tv_priceTag.setText("悬赏金：");
                et_normalPrice.setHint("输入悬赏金额");
                et_normalPrice.setText(Utils.moneyFormat(topic.getPrice()));
                showNormalPriceLayout();
                hideAcutionPriceLayout();
                initMoneyInputLister();
                break;
            case Constant.TOPIC_TYPE_FOUND:
                titleBar.setRightTitle(EditTopicActivity.TOPIC_TYPE_FOUND);
                hidePriceLayout();
                break;
            case Constant.TOPIC_TYPE_GIFT:
                titleBar.setRightTitle(EditTopicActivity.TOPIC_TYPE_GIFT);
                hidePriceLayout();
                break;
            case Constant.TOPIC_TYPE_GOODS:
                titleBar.setRightTitle(EditTopicActivity.TOPIC_TYPE_GOODS);
                tv_priceTag.setText("售价：");
                et_normalPrice.setHint("输入出售金额");
                showNormalPriceLayout();
                hideAcutionPriceLayout();
                break;
            case Constant.TOPIC_TYPE_AUCTION:
                titleBar.setRightTitle(EditTopicActivity.TOPIC_TYPE_AUCTION);
                tv_priceTag.setText("起拍价：");
                showAcutionPriceLayout();
                showNormalPriceLayout();
                break;
            case Constant.TOPIC_TYPE_SHOW:
                titleBar.setRightTitle(EditTopicActivity.TOPIC_TYPE_SHOW);
                hidePriceLayout();
                break;
        }
    }

    private void showNormalPriceLayout() {
        //if (rl_NormalPrice.getVisibility() != View.VISIBLE) {
        if (!rl_NormalPrice.isShown()) {
            rl_NormalPrice.setVisibility(View.VISIBLE);
        }
    }

    private void hidePriceLayout() {
        hideNormalPriceLayout();
        hideAcutionPriceLayout();
    }

    private void hideNormalPriceLayout() {
        // if (rl_NormalPrice.getVisibility() == View.VISIBLE) {
        if (rl_NormalPrice.isShown()) {
            rl_NormalPrice.setVisibility(View.GONE);
        }
    }

    private void hideAcutionPriceLayout() {
        //if (ll_auction.getVisibility() == View.VISIBLE) {
        if (ll_acution.isShown()) {
            ll_acution.setVisibility(View.GONE);
        }
    }

    private void initMoneyInputLister() {

        if (inputCheck != null) {
            return;
        }
        inputCheck = new MoneyInputCheck(this, 0.01, new MoneyInputCheck.InteractionListener() {
            @Override
            public void showErrorMessage(String message) {
                et_normalPrice.setError(message);
                btn_publish.setEnabled(false);
            }

            @Override
            public void waitInput() {
               // btn_publish.setEnabled(false);
            }

            @Override
            public void inputRight() {
                btn_publish.setEnabled(true);
            }
        });

        et_normalPrice.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                inputCheck.onTextChanged(s);
            }

            @Override
            public void afterTextChanged(Editable s) {
                inputCheck.afterTextChanged(s);
            }
        });

    }

    private void showAcutionPriceLayout() {
        //if (ll_auction.getVisibility() != View.VISIBLE) {
        if (!ll_acution.isShown()) {
            ll_acution.setVisibility(View.VISIBLE);
        }
    }

    private void initLocation() {
        location = new GaodeLocationClient(this, true);
        location.setLocationListener(new GaodeLocationClient.LocationListener() {
            @Override
            public void locationSuccess(AMapLocation location) {
                latLng = new LatLng(location.getLatitude(), location.getLongitude());
                str_address = location.getAddress();
                tv_address.setText(str_address);
            }
        });
    }


    @OnClick(R.id.ll_date_choose)
    void dateChoose() {
        DateChooseDialog dateChooseDialog = new DateChooseDialog(this);
        dateChooseDialog.setOnDateChooseListener(new DateChooseDialog.DateChooseInterface() {
            @Override
            public void getDateTime(Date startDate, Date stopDate) {
                tv_startDate.setText(DateUtils.getTimestampString(startDate));
                tv_stopDate.setText(DateUtils.getTimestampString(stopDate));
            }

        });
        dateChooseDialog.getWindow().setGravity(Gravity.BOTTOM | Gravity.FILL_HORIZONTAL);
        dateChooseDialog.getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
        dateChooseDialog.show();
    }

    private void startRecordVideo() {
        long SDCardRemainMB = FileUtils.getSDFreeSize();
        if (SDCardRemainMB >= 0L && SDCardRemainMB < 2L) {
            showToast(getString(R.string.aliwx_no_enough_sdcard_size));
            return;
        }


        //ShortVideoKitProcesser.showRecordShortVideo(PublishTopicActivity.this, null, REQUEST_CODE_RECORD_VIDEO, SITUATION_FOR_PUBLISH, "high", 0, 0);//阿里百川短视频录制
        // startActivityForResult(new Intent(this, VideoRecordActivity.class), REQUEST_CODE_RECORD_VIDEO);
        // startActivityForResult(new Intent(this, FFmpegVideoRecordActivity.class), REQUEST_CODE_RECORD_VIDEO);
        VideoRecordActivityV3.startActivity(this, REQUEST_CODE_RECORD_VIDEO, true);
    }

    private void showVideo(String videoPath) {
        Uri uri = Uri.parse("http://svideo.m.taobao.com/av/implayer.html");
        Intent intent = new Intent("android.intent.action.VIEW", uri, this, MyVideoPlayActivity.class);
        intent.putExtra("videoPath", videoPath);
        intent.putExtra("framePicPath", framePicPath);
        intent.putExtra("videoSize", videoSize);
        startActivity(intent);
    }

    private String strTimeToDateFormat(String yearStr, String dateStr, String hourStr, String minuteStr) {

        return yearStr.replace("年", "-") + dateStr.replace("月", "-").replace("日", " ")
                + hourStr + ":" + minuteStr;
    }


    @OnClick(R.id.rl_description)
    void desc() {
        et_content.setFocusable(true);
        et_content.setFocusableInTouchMode(true);
        et_content.requestFocus();
        inputMethodManager.toggleSoftInput(0, InputMethodManager.SHOW_FORCED);
    }

    @OnClick(R.id.rl_location)
    void location() {
        Intent intent = new Intent(EditTopicActivity.this, PickLocationMapActivity.class);
        if (latLng != null) {
            intent.putExtra(PickLocationMapActivity.EXTRA_DATA_LATITUDE, latLng.getLatitude());
            intent.putExtra(PickLocationMapActivity.EXTRA_DATA_LONGITUDE, latLng.getLongitude());
        }
        startActivityForResult(intent, REQUEST_CODE_LOCATION);
    }

    @OnClick(R.id.btn_publish)
    void publish() {
        hideSoftKeyboard();
        if (topicType == null) {
            showToast("请在右上角选择分类");
            return;
        }
        // final AmapTopic topic = new AmapTopic();//如果是发布到自己的ElasticSearch,则应该是:Topic topic= new Topic;

        String str_goodsTitle = et_goodsTitle.getText().toString().trim();
        if (TextUtils.isEmpty(str_goodsTitle)) {

            // Toast.makeText(PublishTopicActivity.this, "商品标题还没设置哦", Toast.LENGTH_LONG).show();
            showToast("标题没设置");
            return;
        }
        if (totalSelectFile.size() == 0) {

            showToast("视频和图片不能同时为空");
            return;
        }
        String str_normalPrice = et_normalPrice.getText().toString().trim();
        newPrice = Utils.moneyFormatStringToDouble(str_normalPrice);
        if (topicType == Constant.TOPIC_TYPE_GOODS) {
            if (Double.compare(newPrice, 0.0) <= 0) {
                showToast("价格还没设置");
                return;
            }
            topic.setPrice(newPrice);
        } else if ((topicType == Constant.TOPIC_TYPE_REWARD)) {
            if (Double.compare(newPrice, 0.0) <= 0) {
                showToast(btn_publish, "悬赏金额还没有设置");
                return;
            }
        } else if (topicType == Constant.TOPIC_TYPE_AUCTION) {
            if (Double.compare(newPrice, 0.0) <= 0) {
                showToast(btn_publish, "起拍价没设置");
                return;
            }
            String str_deposit = et_deposit.getText().toString();
            if (Double.compare(newPrice, 0.0) <= 0) {
                showToast(btn_publish, "商品保证金没设置");
                return;
            }
            String str_bidIncrement = et_bidIncrement.getText().toString();
            if (TextUtils.isEmpty(str_bidIncrement)) {
                showToast(btn_publish, "商品加价幅度没设置");
                return;
            }

            if (startDate == null) {
                showToast(btn_publish, "开拍时间没设置");
                return;
            }
            topic.setPrice(newPrice);
            topic.setAuctionPrice(Utils.moneyFormatStringToDouble(str_normalPrice));
            topic.setDeposit(Utils.moneyFormatStringToDouble(str_deposit));
            topic.setBidIncrement(Utils.moneyFormatStringToDouble(str_bidIncrement));
            topic.setStartTime(startDate);
            topic.setStopTime(stopDate);
        }

        String content = et_content.getText().toString().trim();

        if (!TextUtils.isEmpty(content)) {
            topic.setContent(content);
        } else {
            topic.setContent("");
        }
        //因为是保存在ES里面，所以每条发布的信息里面，都冗余保存发布者信息，也许这样是不科学的，以后再考量
        User loginUser = UserProfileManager.getInstance().getLoginUserInfo();


        topic.setTitle(str_goodsTitle);
        User author = new User(loginUser.getuId());
        author.setAvatar(loginUser.getAvatar());
        author.setUsername(loginUser.getUsername());
        topic.setManager(author);


        topic.setUpdated(new Date());
        //如果是焦点类型，
        if (topic.getType() == Constant.TOPIC_TYPE_SCHOOL || topic.getType() == Constant.TOPIC_TYPE_AREA || topic.getType() == Constant.TOPIC_TYPE_INDUSTRY) {

            if (topic.getStatus() == Constant.TOPIC_STATUS_NORMAL) { //状态是普通状态，非审核失败状态和等待审核状态，那么禁止对标题编辑
                et_goodsTitle.setEnabled(false);
                et_goodsTitle.setOnClickListener(v -> {
                    ConfirmDialog dialog = new ConfirmDialog(EditTopicActivity.this, "提示", "暂时不能编辑标题");
                    dialog.show();
                });
            }

        } else {//???
            // topic.setStatus(Constant.TOPIC_STATUS_NORMAL);

        }
        topic.setType(topicType);
        if (latLng != null) {
            topic.setLocation(latLng);
            topic.setAddress(str_address);
        } else {
            topic.setAddress(UserProfileManager.getInstance().getUserArea());
        }
        //如果是悬赏主题，判断保证金是否已经修改了

        uploadFile();

    }

    private void uploadFile() {
        FileUpLoad fileUpLoad = new FileUpLoad(EditTopicActivity.this, totalSelectFile, new FileUpLoad.InteractionListener() {
            @Override
            public void onShowToast(String content) {
                showToast(findViewById(R.id.btn_publish), content);
            }

            @Override
            public void onShowProgressBar(String content) {
                showProgressDialog(content);
            }

            @Override
            public void onHideProgressBar() {
                hideProgressDialog();
            }

            @Override
            public void onUploadComplete() {
                //清掉数据
                topic.setHadPraise(null);
                topic.setHadReceive(null);
                if (topic.getType() == Constant.TOPIC_TYPE_SCHOOL || topic.getType() == Constant.TOPIC_TYPE_AREA || topic.getType() == Constant.TOPIC_TYPE_INDUSTRY) {
                    updateLiveRoomTopic();
                } else if ((topicType == Constant.TOPIC_TYPE_REWARD)) {
                    checkAmountChange();
                } else {
                    updateTopic();
                }


            }

        });

        fileUpLoad.run();
    }

    private void checkAmountChange() {

        Double originalPrice = topic.getPrice();
        if (originalPrice.compareTo(newPrice) > 0) {//告知用户，将减少保证金
            String tips = "修改悬赏，减少保证金，将退回";
            PayPasswordDialog payPasswordDialog = new PayPasswordDialog(this, tips, originalPrice - newPrice);
            payPasswordDialog.setOnConfirmListener(new PayPasswordDialog.OnConfirmListener() {
                @Override
                public void onCommit(String passWord) {
                    //  doOffer(offerAmount.doubleValue(), passWord);
                    topic.setPrice(newPrice);
                    updateRewardTopic(passWord);
                }
            });
            payPasswordDialog.show();
        } else if (originalPrice.compareTo(newPrice) < 0) {//告知用户，将增加保证金
            double amount = newPrice - originalPrice;
            String tips = "修改悬赏，增加保证金";
            new PayUtils(this, amount, tips, true, new PayUtils.InteractionListener() {
                @Override
                public void onPrepareComplete(String payPassword) {
                    topic.setPrice(newPrice);
                    updateRewardTopic(payPassword);
                }
            });

//            PayPasswordDialog payPasswordDialog = new PayPasswordDialog(this, tips, amount);
//            payPasswordDialog.setOnConfirmListener(new PayPasswordDialog.OnConfirmListener() {
//                @Override
//                public void onCommit(String payPassword) {
//                    //  doOffer(offerAmount.doubleValue(), passWord);
//                    topic.setPrice(newPrice);
//                    updateRewardTopic(payPassword);
//                }
//            });
//            payPasswordDialog.show();
        } else {
            updateRewardTopic(null);
        }

    }

    /**
     * 更新topic，保存到自己服务器中
     */
    private void updateTopic() {
        if (!Helper.getInstance().isNetworkConnected()) {
            showToast_v1(getString(R.string.network_anomalies));
            return;
        }
        showProgressDialog("正在保存...");
        btn_publish.setEnabled(false);
        List<MyFile> uploadList = new ArrayList<>();
        for (MyFile myFile : totalSelectFile) {
            if (myFile.getStatus() != MyFile.FILE_STATUS_UPLOAD_FAIL) {//只要不是上传失败的，包括远程的，已经传功的，都给保存到服务端
                uploadList.add(myFile);
            }
        }
        topic.setMyFileList(uploadList);
        topic.setVideo("");//视频连接设置为空，如果上传的文件中有视频文件，在服务端会 保存进主题里面，如果没有上传视频文件，就会以空保存
        //更新之前清空之前设置的图片，文件都放MyFileList 中上传
        topic.setPictures(null);
        RetrofitManager.getInstance()
                .createRequest(TopicService.class)
                .update(topic)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        hideProgressDialog();
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "更新到ES失败：" + response.message());
                            showToast(getString(R.string.system_busy));
                            return;
                        }

                        if (result.isError()) {
                            Log.e(TAG, "更新到ES失败：" + result.getMsg());
                            showToast(getString(R.string.system_busy));
                            return;
                        }
                        Log.d(TAG, "更新到ES完成");
                        updateFileStatus(uploadList);
                        updateSuccess(uploadList);
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        Log.e(TAG, "更新到ES失败：" + t.getMessage());
                        t.printStackTrace();
                        hideProgressDialog();
                        showToast(getString(R.string.system_busy));
                    }
                });
    }


    /**
     * 更新 直播类主题
     */
    private void updateLiveRoomTopic() {
        if (!Helper.getInstance().isNetworkConnected()) {
            showToast_v1(getString(R.string.network_anomalies));
            return;
        }
        showProgressDialog("正在保存...");
        btn_publish.setEnabled(false);
        List<MyFile> uploadList = new ArrayList<>();
        for (MyFile myFile : totalSelectFile) {
            if (myFile.getStatus() != MyFile.FILE_STATUS_UPLOAD_FAIL) {//只要不是上传失败的，包括远程的，已经上传成功的，都给保存到服务端
                uploadList.add(myFile);
            }
        }
        topic.setMyFileList(uploadList);
        topic.setVideo("");//视频连接设置为空，如果上传的文件中有视频文件，在服务端会 保存进主题里面，如果没有上传视频文件，就会以空保存
        //更新之前清空之前设置的图片，文件都放MyFileList 中上传
        topic.setPictures(null);

        RetrofitManager.getInstance().createRequest(TopicService.class)
                .updateLiveRoomTopic(topic)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        btn_publish.setEnabled(true);
                        hideProgressDialog();
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "更新直播类主题失败：" + response.message());
                            showToast(getString(R.string.system_busy));
                            return;
                        }
                        if (result.isError()) {
                            Log.e(TAG, "更新直播类主题失败：" + result.getMsg());

                            showToast(btn_publish, getString(R.string.system_busy));
                            return;
                        }
                        Log.i(TAG, "onResponse: 更新直播类主题完成");
                        updateFileStatus(uploadList);
                        updateSuccess(uploadList);

                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        btn_publish.setEnabled(true);
                        hideProgressDialog();
                    }
                });


    }

    /**
     * 更新悬赏类型主题
     */
    private void updateRewardTopic(String payPassword) {
        if (!Helper.getInstance().isNetworkConnected()) {
            showToast_v1(getString(R.string.network_anomalies));
            return;
        }
        showProgressDialog("正在保存...");
        btn_publish.setEnabled(false);
        List<MyFile> uploadList = new ArrayList<>();
        for (MyFile myFile : totalSelectFile) {
            if (myFile.getStatus() != MyFile.FILE_STATUS_UPLOAD_FAIL) {//只要不是上传失败的，包括远程的，已经传功的，都给保存到服务端
                uploadList.add(myFile);
            }
        }
        topic.setMyFileList(uploadList);
        topic.setVideo("");//视频连接设置为空，如果上传的文件中有视频文件，在服务端会 保存进主题里面，如果没有上传视频文件，就会以空保存
        //更新之前清空之前设置的图片，文件都放MyFileList 中上传
        topic.setPictures(null);
        Map<String, Object> body = new HashMap<>();
        body.put("topic", topic);
        if (payPassword != null) {
            body.put("payPassword", payPassword);
        }
        RetrofitManager.getInstance()
                .createRequest(TopicService.class)
                .updateRewardTopic(body)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        btn_publish.setEnabled(true);
                        hideProgressDialog();
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "更新悬赏主题失败：" + response.message());
                            showToast(getString(R.string.system_busy));
                            return;
                        }

                        if (result.isError()) {
                            Log.e(TAG, "更新悬赏主题失败：" + result.getMsg());
                            switch (result.getStatus()) {
                                case Constant.TOPIC_STATUS_ERROR:
                                    showToast(btn_publish, "状态有误，不能做编辑操作");
                                    break;
                                case Constant.PAY_PASSWORD_ERROR:
                                    showToast(btn_publish, getString(R.string.pay_password_error));
                                    updateFileStatus(uploadList);
                                    break;
                                case Constant.BALANCE_NOT_ENOUGH:
                                    showToast(btn_publish, getString(R.string.balance_not_enough));
                                    Object data = result.getData();
                                    if (data != null) {//当提示余额不足时候，后端会返回用户余额信息
                                        User user = ((JSONObject) data).toJavaObject(User.class);
                                        UserProfileManager.getInstance().syncLoginUserInfo(user);
                                    }
                                    break;
                                default:
                                    showToast(btn_publish, getString(R.string.system_busy));
                            }
                            return;
                        }
                        Log.d(TAG, "更新悬赏主题完成");
                        Object data = result.getData();
                        if (data != null) {
                            //更新用户本地保证金数额
                            double deposit = ((BigDecimal) data).doubleValue();
                            UserProfileManager.getInstance().setDeposit(deposit);
                        }
                        updateFileStatus(uploadList);
                        updateSuccess(uploadList);
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        btn_publish.setEnabled(true);
                        Log.e(TAG, "更新到ES失败：" + t.getMessage());
                        t.printStackTrace();
                        hideProgressDialog();
                        showToast(getString(R.string.system_busy));
                    }
                });
    }

    private void updateSuccess(List<MyFile> uploadList) {
        List<String> pictures = new ArrayList<>();
        for (MyFile myFile : uploadList) {
            if (myFile.getType() == MyFile.FILE_TYPE_PICTURE) {
                pictures.add(myFile.getUrl());
            } else {
                topic.setVideo(myFile.getUrl());
                topic.setVideoCover(myFile.getVideoCover());
            }
        }
        topic.setPictures(pictures);
        isUpdate = true;
        //setResult(RESULT_OK, new Intent().putExtra(Constant.EXTRA_INFO_TOPIC, topic));
        //跨了activity ，用广播把更新后的topic 传递出去
        LocalBroadcastManager broadcastManager = LocalBroadcastManager.getInstance(EditTopicActivity.this);
        broadcastManager.sendBroadcast(new Intent(Constant.ACTION_TOPIC_EDIT_CHANGED).putExtra(Constant.EXTRA_INFO_TOPIC, topic));
        ConfirmDialog dialog = new ConfirmDialog(EditTopicActivity.this, "提醒", "更新完成,去看看？", true);
        dialog.setConfirmListener(
                new ConfirmDialog.ConfirmListener() {
                    @Override
                    public void confirm() {
                        //通知
                        startActivity(new Intent(EditTopicActivity.this, TopicDetailsActivity.class).putExtra(Constant.EXTRA_INFO_TOPIC, topic));
                    }
                });
        dialog.setCancelListener(new ConfirmDialog.CancelListener() {
            @Override
            public void cancel() {
                onBackPress();
            }
        });
        dialog.show();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK || data == null) {
            return;
        }
        switch (requestCode) {
            case REQUEST_CODE_PICTURE_CHOOSE:

                ArrayList<MyFile> pictureFiles = data.getParcelableArrayListExtra("pictureFiles");
                ArrayList<MyFile> videoFiles = data.getParcelableArrayListExtra("videoFiles");
                totalSelectFile.removeAll(selectRemoteVideos);
                selectRemoteVideos.clear();
                if (videoFiles != null && videoFiles.size() != 0) {
                    selectRemoteVideos.addAll(videoFiles);
                    totalSelectFile.addAll(0, videoFiles);
                    // picturesListView.refreshVideoItem(videoFiles.get(0));
                }
                totalSelectFile.removeAll(selectRemotePictures);
                selectRemotePictures.clear();
                if (pictureFiles != null && pictureFiles.size() != 0) {
                    selectRemotePictures.addAll(pictureFiles);
                    totalSelectFile.addAll(pictureFiles);
                }
                picturesListView.refresh();

                break;

            case REQUEST_CODE_RECORD_VIDEO:

                framePicPath = data.getStringExtra("coverPath");
                //视频本地路径
                String localVideoPath = data.getStringExtra("videoPath");
                videoSize = data.getIntExtra("videoSize", 0);
                totalSelectFile.removeAll(selectLocalVideos);
                selectLocalVideos.clear();
                MyFile localVideoFile = new MyFile(localVideoPath, framePicPath, MyFile.FILE_TYPE_VIDEO, MyFile.FILE_STATUS_LOCAL);
                selectLocalVideos.add(localVideoFile);
                totalSelectFile.addAll(0, selectLocalVideos);//插到第一个的位置
                picturesListView.refresh();
                break;

            case REQUEST_CODE_LOCATION:
                double latitude = data.getDoubleExtra("latitude", 0);
                double longitude = data.getDoubleExtra("longitude", 0);
                latLng.setLatitude(latitude);
                latLng.setLongitude(longitude);
                str_address = data.getStringExtra("address");
                tv_address.setText(str_address);
                Log.d(TAG, "onActivityResult: 收到定位回传");
                break;
        }
    }

    public void compressAndGenImage(Bitmap image, String outPath, String imgName) throws IOException {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        // scale
        int options = 100;
        // Store the bitmap into output stream(no compress)
        image.compress(Bitmap.CompressFormat.JPEG, 80, os);
        // Compress by loop
//        while (os.toByteArray().length / 1024 > maxSize) {
//            // Clean up os
////            int i = os.toByteArray().length / 1024;
////            options = maxSize / i * 100;
//
//
//            os.reset();
//            // interval 10
//            options -= 10;
//
//            image.compress(Bitmap.CompressFormat.JPEG, options, os);
//        }

        // Generate compressed image file

        File dirFile = new File(outPath);
        if (!dirFile.exists()) {
            dirFile.mkdir();
        }
        FileOutputStream fos = new FileOutputStream(outPath + imgName);
        fos.write(os.toByteArray());
        fos.flush();
        fos.close();
    }


    @Override
    protected void onResume() {

        super.onResume();
    }

    @Override
    protected void onDestroy() {

        super.onDestroy();
        PermissionsUtils.getInstance().clear();
    }


    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            onBackPress();
            return true;

        } else {
            return super.onKeyDown(keyCode, event);
        }
    }


    private void onBackPress() {
        if (previewSelectFilePageView.isShown()) {
            if (!previewSelectFilePageView.isShowAnimate()) {
                Info info = onGetPhotoViewInfo(previewSelectFilePageView.getCurrentItem());
                previewSelectFilePageView.hideBigPictures(info);
            }
            return;
        }
        String str_content = et_content.getText().toString().trim();
        if (isUpdate) {
            setResult(RESULT_OK, new Intent().putExtra(Constant.EXTRA_INFO_TOPIC, topic));
            finish();
            return;
        }


        if (!TextUtils.isEmpty(str_content) || totalSelectFile.size() != 0) {
            ConfirmDialog dialog = new ConfirmDialog(EditTopicActivity.this, "提醒", "放弃修改？", true);
            dialog.show();
            dialog.setConfirmListener(new ConfirmDialog.ConfirmListener() {
                @Override
                public void confirm() {
                    finish();
                }
            });
        } else {
            finish();
        }
    }


    @Override
    public Info onGetPhotoViewInfo(int position) {
        MyFile myFile = totalSelectFile.get(position);
        return picturesListView.getPositionInfo(myFile);
    }


    @Override
    public void onSelectRemoteFile() {
        ArrayList<MyFile> historySelectFile = new ArrayList<>();
        historySelectFile.addAll(totalSelectFile);//添加总的
        historySelectFile.removeAll(selectLocalVideos);
        historySelectFile.removeAll(selectLocalPictures);
        MyFileSelectActivity.startActivity(this, videoLimit - selectLocalVideos.size(), pictureLimit - selectLocalPictures.size(), false, historySelectFile, REQUEST_CODE_PICTURE_CHOOSE);

    }

    @Override
    public void onPickNewPicture(int position) {
// TODO: 2019/7/4

//        Matisse.from(EditTopicActivity.this)
//                .choose(MimeType.ofImage())
//                .countable(true)
//                .showSingleMediaType(true)
//                .maxSelectable(pictureLimit - selectRemotePictures.size())
//                .theme(R.style.choose_pictures_style)
//                // .addFilter(new (320, 320, 5 * Filter.K * Filter.K))
//                .gridExpectedSize(
//                        getResources().getDimensionPixelSize(R.dimen.grid_expected_size))
//                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
//                .thumbnailScale(0.85f)
//                .imageEngine(new GlideEngine())
//                .forResult(REQUEST_CODE_PICTURE_CHOOSE);

        EasyPhotos.createAlbum(this, true, GlideEngine.getInstance())
                .setFileProviderAuthority("com.srbl.mytx.fileProvider")
                .setSelectedPhotos(selectPhotos)
                .setCount(9)
                .start(new SelectCallback() {
                    @Override
                    public void onResult(ArrayList<Photo> photos, boolean isOriginal) {
                        selectPhotos = photos;
                        totalSelectFile.removeAll(selectLocalPictures);
                        selectLocalPictures.clear();
                        for (Photo photo : photos) {
                            selectLocalPictures.add(new MyFile(photo.uri, MyFile.FILE_TYPE_PICTURE, MyFile.FILE_STATUS_LOCAL));
                        }
                        totalSelectFile.addAll(selectLocalPictures);
                        picturesListView.refresh();
                        previewSelectFilePageView.refresh();
                    }
                });
    }

    @Override
    public void onShowBigImage(MyFile targetFile, Info info) {
        previewSelectFilePageView.showBigPictures(totalSelectFile.indexOf(targetFile), info);
    }

    @Override
    public void onCreateVideo(View view, int position) {
        //拍摄短视频
        startRecordVideo();
    }

    @Override
    public void onShowVideo(MyFile targetVideoFile, int position) {
        //展示短视频
        String loadUrl;
        if (targetVideoFile.getStatus() != MyFile.FILE_STATUS_REMOTE) {
            loadUrl = targetVideoFile.getUrl();
        } else {
            loadUrl = AliOssService.TOPIC_VIDEO_PRE_URL + targetVideoFile.getUrl();
        }
        showVideo(loadUrl);

    }

    @Override
    public void onPictureRemove(int position, MyFile targetPictureFile) {
        if (targetPictureFile.getStatus() == MyFile.FILE_STATUS_REMOTE) {
            selectRemotePictures.remove(targetPictureFile);
        } else {
            selectLocalPictures.remove(targetPictureFile);
            //清除掉已选文件记录
            for (int i = 0; i < selectPhotos.size(); i++) {
                if (selectPhotos.get(i).uri.equals(targetPictureFile.getUri())) {
                    selectPhotos.remove(i);
                    break;
                }
            }
        }
        previewSelectFilePageView.refresh();

    }

    @Override
    public void onVideoRemove(int position, MyFile targetVideoFile) {
        if (targetVideoFile.getStatus() == MyFile.FILE_STATUS_REMOTE) {
            selectRemoteVideos.remove(targetVideoFile);
        } else {
            selectLocalVideos.remove(targetVideoFile);
        }
        previewSelectFilePageView.refresh();

    }

    /**
     * 保存到服务后，把已经保存的图片的状态设置为 远程图片
     * 不然连续发布，服务端把图片当成新上传图片传，插入到数据库被报ID重复的错
     *
     * @param uploadList
     */
    private void updateFileStatus(List<MyFile> uploadList) {
        for (MyFile myFile : uploadList) {
            if (myFile.getStatus() == MyFile.FILE_STATUS_UPLOAD_SUCCESS) {
                myFile.setStatus(MyFile.FILE_STATUS_REMOTE);
                //从本地文件选择集合中  移动到  远程文件选择集合中，并刷新
                if (myFile.getType() == MyFile.FILE_TYPE_PICTURE) {
                    selectLocalPictures.remove(myFile);
                    selectRemotePictures.add(myFile);
                } else {
                    selectLocalVideos.remove(myFile);
                    selectRemoteVideos.add(myFile);
                }
                picturesListView.refresh();
            }
        }
    }


    @Override
    protected void onStart() {
        super.onStart();
        String[] permissions = new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.RECORD_AUDIO, Manifest.permission.CAMERA};
        PermissionsUtils.getInstance().checkPermissions(this, permissions, this);

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        PermissionsUtils.getInstance().onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    public void onGranted() {

    }

    @Override
    public void onDenied(List<String> deniedPermissionList) {
        StringBuilder tips = new StringBuilder();
        for (String permission : deniedPermissionList) {
            if (Manifest.permission.ACCESS_FINE_LOCATION.equals(permission)) {
                tips.append("[位置] ");
            } else if (Manifest.permission.READ_EXTERNAL_STORAGE.equals(permission) || Manifest.permission.WRITE_EXTERNAL_STORAGE.equals(permission)) {
                tips.append("[储存空间] ");
            } else if (Manifest.permission.RECORD_AUDIO.equals(permission)) {
                tips.append("[麦克风] ");
            } else if (Manifest.permission.CAMERA.equals(permission)) {
                tips.append("[相机] ");
            }
        }
        ConfirmDialog dialog = new ConfirmDialog(EditTopicActivity.this, "提醒", "使用 " + tips + "的权限被禁止，去设置？", "去设置", "取消", true);
        dialog.setConfirmListener(new ConfirmDialog.ConfirmListener() {
            @Override
            public void confirm() {
                Uri packageURI = Uri.parse("package:" + getPackageName());
                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI);
                startActivity(intent);
            }
        });
        dialog.setCancelListener(new ConfirmDialog.CancelListener() {
            @Override
            public void cancel() {
                finish();
            }
        });
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
    }
}
